package com.chen.utils.controller;

import com.chen.base.utils.CommonUtil;
import com.chen.base.utils.JdbcUtil;
import com.chen.root.base.R;
import com.chen.utils.entity.DataSourceInfo;
import com.chen.utils.handler.GenerateBeforeHandler;
import com.chen.utils.params.GeneratingParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author: Long
 * @date: 2023/6/27 21:29
 **/
@Slf4j
@Validated
@RestController
@RequestMapping("/generate")
@Api(tags = "代码生成管理API")
public class GenerateController {
    @Resource
    private GenerateBeforeHandler generateBeforeHandler;

    @PostMapping
    @ApiOperation("生成java文件")
    public void generateJavaFile(@RequestBody @Validated GeneratingParam param){
        generateBeforeHandler.handler(param);
    }

    @PostMapping("/connect")
    @ApiOperation("测试数据源连接")
    public R<String> connect(@RequestBody @Validated DataSourceInfo param){
        try {
            String logStr = "\n\n==========================测试连接数据源==========================\n{}\n";
            log.info(logStr, CommonUtil.toStr(param));

            JdbcUtil.testConnect(param.getDataType(), param.getUrl(), param.getUsername(), param.getPassword());
            return R.ok(null,"连接成功！");
        }catch (Exception e){
            log.error("连接数据源异常: ", e);
            return R.failed(null,"连接数据源失败：" + e.getMessage());
        }
    }
}
